package com.young.trigger.service;

import com.young.common.Result;
import com.young.common.ResultBuilder;
import com.young.core.domain.NodeDO;
import com.young.core.domain.ProjectDO;
import com.young.core.domain.TraceDO;
import com.young.core.manager.NodeManager;
import com.young.core.manager.ProjectManager;
import com.young.core.manager.TraceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NodeServiceImpl implements NodeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(NodeService.class);

    @Autowired
    private NodeManager nodeManager;

    @Autowired
    private ProjectManager projectManager;

    @Autowired
    private TraceManager traceManager;

    @Override
    public Result registry(NodeDO node) {
        Result result = ResultBuilder.create();
        try {
            String pn = node.getProject();
            ProjectDO project = projectManager.get(pn, false);
            if (project == null) {
                return ResultBuilder.notFound("项目不存在");
            }
            nodeManager.upsert(node);
            result.setSuccess(true);
        } catch (Exception e) {
            LOGGER.error("客户端节点注册失败,{}:{}", node.getIp(), node.getPort(), e);
            result.exception(e);
        }
        return result;
    }

    @Override
    public Result unregister(NodeDO node) {
        Result result = ResultBuilder.create();
        try {
            String pn = node.getProject();
            ProjectDO project = projectManager.get(pn, false);
            if (project == null) {
                return ResultBuilder.notFound("项目不存在");
            }
            this.nodeManager.delete(node);
            result.setSuccess(true);
        } catch (Exception e) {
            LOGGER.error("客户端节点取消注册失败,{}:{}", node.getIp(), node.getPort(), e);
            result.exception(e);
        }
        return result;
    }

    @Override
    public Result callback(String traceId, TraceDO.NodeTrace nodeTrace) {
        Result result = ResultBuilder.create();
        try {
            LOGGER.info("收到任务回调请求,traceId - {},status - {},index - {},duration - {}",
                    traceId,
                    nodeTrace.getStatus(),
                    nodeTrace.getIndex(),
                    nodeTrace.getDuration());
            traceManager.append(traceId, nodeTrace);
            result.setSuccess(true);
        } catch (Exception e) {
            LOGGER.error("任务回调失败,traceId:{}, index:{}, status:{}", traceId, nodeTrace.getIndex(), nodeTrace.getStatus(), e);
            result.exception(e);
        }
        return result;
    }

}
